<template>
  <div class="user-info">
    <user-avatar ref="avatar" :cUserAvatar="userinfo.avatar"></user-avatar>
    <el-form
      :model="userinfo"
      ref="ruleForm"
      label-width="80px"
      style="margin-top: 40px"
    >
      <el-form-item label="昵称：" prop="nickName">
        <el-input v-model="userinfo.nickName" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="姓名：" prop="realName">
        <el-input v-model="userinfo.realName" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input v-model="userinfo.phone" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="身份证：" prop="identityNum">
        <el-input
          v-model="userinfo.identityNum"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址：" prop="address">
        <el-input v-model="userinfo.address" style="width: 300px"></el-input>
      </el-form-item>
    </el-form>
    <el-button style="margin-left: 310px" type="success" @click="updateInfo"
      >修改</el-button
    >
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import UserAvatar from "../components/UserAvatar.vue";
import { loginUpdateByUsername, loginSelectByUsername } from "../api/user";
import { useUserInfoStore } from "../stores/user";

const userStore = useUserInfoStore();
const userinfo = userStore.userinfo;
const ruleForm = ref(null);
const avatarRef = ref(null);

const updateInfo = () => {
  // ... 验证代码 ...
  userinfo.avatar = avatarRef.value.cUserAvatar;
  loginUpdateByUsername({
    realName: userinfo.realName, // 真实姓名
    nickName: userinfo.nickName, // 昵称
    phone: userinfo.phone, // 手机号
    identityNum: userinfo.identityNum, // 身份证号码
    address: userinfo.address, // 地址
    avatar: userinfo.avatar, // 头像
  })
    .then((res) => {
      if (res.flag) {
        // 处理成功情况，例如更新状态或显示消息
        console.log("res", res);
        console.log("this.userinfo", userinfo);
        alert(res.message);
      } else {
        // 处理失败情况，例如显示错误消息
        alert(res.data);
      }
    })
    .catch((err) => {
      // 处理错误情况，例如显示错误消息
      alert(err.message);
    });
};

onMounted(() => {
  loginSelectByUsername({}).then((res) => {
    console.log(res);
    userStore.updateUserInfo(res.data); // 使用 Pinia 的 action 更新用户信息
  });
});
</script>

<style lang="less" scoped>
.user-info {
  margin: 0px auto;
  width: 900px;
  float: left;
  padding-left: 20px;
  background: #fff;
  height: 100%;
  min-height: 600px;
}
</style>